package org.jash.shop;

import android.content.Intent;
import android.os.Bundle;
import android.widget.EditText;
import android.widget.Toast;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;

import org.jash.shop.entity.LoginEntity;

import java.util.HashMap;

public class MainActivity extends AppCompatActivity {
    private EditText username, password;
    private ActivityResultLauncher<Intent> launcher;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        username = findViewById(R.id.username);
        password = findViewById(R.id.password);
        launcher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), i -> {
            Intent data = i.getData();
            if (data != null) {
                username.setText(data.getStringExtra("username"));
                password.setText(data.getStringExtra("password"));
            }
        });
        findViewById(R.id.login).setOnClickListener(v -> {
            String un = username.getText().toString();
            String pw = password.getText().toString();
            HttpUtils.doPost("http://10.161.52.111:8080/user/login",
                    new HashMap<String,String>() {{
                        put("username", un);
                        put("password", pw);
                    }}, LoginEntity.class,
                    r -> {
                        if (r.getCode() == 200) {
                            Toast.makeText(this, "登录成功", Toast.LENGTH_SHORT).show();
                            startActivity(new Intent(this, ShopActivity.class));
                        } else {
                            Toast.makeText(this, r.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    },
                    t -> {
                        Toast.makeText(this, t.getMessage(), Toast.LENGTH_SHORT).show();
                    });

        });
        findViewById(R.id.goto_register).setOnClickListener(v -> {
            launcher.launch(new Intent(this, RegisterActivity.class));
        });

    }
}